package com.ruoyi.web.util;

import com.ruoyi.common.utils.file.ImageUtils;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.activiti.engine.task.TaskQuery;
import org.activiti.image.ProcessDiagramGenerator;
import org.activiti.image.impl.DefaultProcessDiagramCanvas;
import org.activiti.image.impl.DefaultProcessDiagramGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
import java.awt.image.RenderedImage;
import java.io.*;
import java.util.*;

@Component
public class ActivityUtils {

    @Autowired
    private ProcessEngine processEngine;

    @Autowired
    RepositoryService repositoryService;
    @Autowired
    TaskService taskService;

    @Autowired
    RuntimeService runtimeService;

    /**
     * 启动工作流
     *
     * @param proKey  工作流
     * @param businessKey  业务主键
     * @param createBy    发起人
     * @param auditBy     审批人
     * @return
     */
    public boolean runProcess(String proKey, String businessKey, String createBy, String auditBy) {
        ProcessInstance processInstance = null;
        try {
            Map variables = new HashMap();
            variables.put("assignee0", createBy);
            variables.put("assignee1", auditBy);
            processInstance = runtimeService.startProcessInstanceByKey(proKey, businessKey, variables);

            System.out.println("流程定义id：" + processInstance.getProcessDefinitionId());
            System.out.println("流程实例id：" + processInstance.getId());
            System.out.println("当前活动Id：" + processInstance.getActivityId());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }


    /**
     * 完成工作任务
     *
     * @param businessKey
     * @param autiRemark 审批意见
     * @param assigneeName assigneeName
     * @return
     */
    public boolean completeTask(String businessKey, String autiRemark,String assigneeName) {
        ProcessInstance processInstance = null;
        try {
            TaskQuery query = taskService.createTaskQuery();
            Task task = query.processInstanceBusinessKey(businessKey).singleResult();
            if(assigneeName.equals(task.getAssignee())){
                //添加审批意见
                if (autiRemark != null && !autiRemark.trim().isEmpty()) {
                    taskService.addComment(task.getId(), task.getProcessInstanceId(), autiRemark);
                }
                //如果有指派人，直接完成任务
                taskService.complete(task.getId());


            }else {
                return false;
            }

        } catch (Exception e) {
            e.printStackTrace();
            return false;

        }
        System.out.println("完成了流程节点"+assigneeName);
        return true;
    }

    /**
     * 生成流程图片
     */
    public InputStream createImg(String proKey, String businessKey) throws IOException {
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();

        //流程定义
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());

        //正在活动节点
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

        DefaultProcessDiagramGenerator pdg = new DefaultProcessDiagramGenerator();

        InputStream inputStream = pdg.generateDiagram(bpmnModel,
                activeActivityIds, //高亮显示的节点
                Collections.emptyList(),//高亮显示的连接线
                "宋体",
                "宋体",
                "宋体");

//        FileOutputStream output = new FileOutputStream(new File("d:/test.svg"));
//        // 生成图片并写入输出流
//        try (InputStream inputStream = pdg.generateDiagram(bpmnModel,  activeActivityIds, Collections.emptyList(),"宋体","宋体","宋体")) {
//            IOUtils.copy(inputStream, output);
//            inputStream.close();
//            output.close();
//        } catch (IOException e) {
//            throw new RuntimeException("Error generating process diagram", e);
//        }
        return  inputStream;

    }


    /**
     * 生成流程图片
     */
    public String createImgBase64(String proKey, String businessKey) throws IOException {
        Task task = taskService.createTaskQuery().processInstanceBusinessKey(businessKey).singleResult();

        List<Task> tasks=taskService.createTaskQuery().processDefinitionKey(proKey).list();
        for (Task task1 : tasks) {
            
        }
        //流程定义
        BpmnModel bpmnModel = repositoryService.getBpmnModel(task.getProcessDefinitionId());

        //正在活动节点
        List<String> activeActivityIds = runtimeService.getActiveActivityIds(task.getExecutionId());

        DefaultProcessDiagramGenerator pdg = new DefaultProcessDiagramGenerator();

        InputStream inputStream = pdg.generateDiagram(bpmnModel,
                activeActivityIds, Collections.emptyList(),
                "宋体","宋体","宋体");

//        FileOutputStream output = new FileOutputStream(new File("d:/test.svg"));
//        // 生成图片并写入输出流
//        try (InputStream inputStream = pdg.generateDiagram(bpmnModel,  activeActivityIds, Collections.emptyList(),"宋体","宋体","宋体")) {
//            IOUtils.copy(inputStream, output);
//            inputStream.close();
//            output.close();
//        } catch (IOException e) {
//            throw new RuntimeException("Error generating process diagram", e);
//        }
        return  inputStreamToBase64(inputStream);

    }


    public String inputStreamToBase64(InputStream inputStream) throws IOException {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096]; // 使用合适的缓冲区大小
            int bytesRead;

            // 将InputStream的内容读取到ByteArrayOutputStream
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, bytesRead);
            }

            // 获取ByteArrayOutputStream中的字节数组
            byte[] fileBytes = baos.toByteArray();

            // 将字节数组转换为Base64字符串
            String base64Svg = Base64.getEncoder().encodeToString(fileBytes);

            // 返回Base64编码的SVG字符串
            return base64Svg;
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
            return "";
        }
    }





}
